/* 导入组件
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaImport\List\components\ImportExcel.tsx
 * @Date: 2021-09-18 14:51:27
 * @LastEditTime: 2021-09-18 15:02:21
 */

import { Button, Col, DatePicker, message, Row, Select, Spin, Upload } from 'antd'
import React, { createRef } from 'react'
import apis from '@/apis/AboutQuota'
import { downBlobFile } from '@/utils/methods'
import { http, UdForm, validators } from '@/lib'
import './approve.scss'
import UdSelect from '@/components/UdFormControls/UdSelect'
import udMainStore from '@/store/UdMain'
import dayjs from 'dayjs'
const { Option } = Select
const { RangePicker } = DatePicker

export default class ImportExcel extends React.Component<any> {
  private form
  // 隐藏掉头曲二曲
  // public hideArr: any = ['头曲', '二曲', '泸州老窖头曲酒类销售有限公司', '泸州老窖二曲酒类销售有限公司']
  // public brandList = udMainStore.brandList.filter(item => this.hideArr.indexOf(item.title) === -1)
  public brandList = udMainStore.brandList
  private data = this.props.data ?? {}
  public cRef = createRef<any>()
  state = {
    fileList: [],
    downloading: false,
    uploading: false,
  }

  componentDidMount() {}

  //下载模板
  private downloadTemplate = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        this.setState({ downloading: true })
        let params = {}
        params['brandCode'] = values.brand.key
        params['brandName'] = values.brand.label
        params['inventoryBegineTime'] = dayjs(values.inventoryTime[0]).format('YYYY-MM-DD 00:00:00')
        params['inventoryEndTime'] = dayjs(values.inventoryTime[1]).format('YYYY-MM-DD 23:59:59')
        http
          .post(apis.getCheckStockTemplate, params, { responseType: 'arraybuffer' })
          .then(res => {
            if (!res.data.code) {
              downBlobFile(res.data, '库存盘点记录模板')
            }
          })
          .finally(() => {
            this.setState({ downloading: false })
          })
      } else {
        console.error(err)
      }
    })
  }

  //上传前操作
  private beforeUpload = file => {
    if (this.state.fileList.length !== 0) {
      message.error('只能上传一个文件')
      return false
    }
    this.setState(state => ({
      fileList: [...state['fileList'], file],
    }))
    return false
  }
  //删除文件
  private onRemove = file => {
    this.setState({ fileList: [] }, () => {
      return true
    })
  }

  private onOk = e => {
    const { fileList } = this.state
    this.form.validateFields((err, values) => {
      if (!err) {
        if (fileList.length === 0) {
          message.warn('请选择导入文件')
          return false
        }
        this.setState({ uploading: true })
        e.drawerBtnLoading()
        const formData = new FormData()
        formData.append('file', fileList[0])
        let params = {
          brandCode: values.brand.key,
          brandName: values.brand.label,
          inventoryBegineTime: dayjs(values.inventoryTime[0]).format('YYYY-MM-DD 00:00:00'),
          inventoryEndTime: dayjs(values.inventoryTime[1]).format('YYYY-MM-DD 23:59:59'),
        }
        formData.append('reqVo', new Blob([JSON.stringify(params)], { type: 'application/json' }))
        http
          .post(apis.importCheckStock, formData, { timeout: 1000 * 60 * 10 })
          .then(() => {
            message.success('操作成功')
            e.close()
          })
          .catch(() => {
            e.drawerBtnLoadingHide()
          })
          .finally(() => {
            this.setState({ uploading: false })
          })
      } else {
        console.log(err)
      }
    })
  }

  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        <UdForm
          getForm={form => (this.form = form)}
          items={[
            {
              label: '品牌公司',
              id: 'brand',
              rules: [validators.required],
              render: <UdSelect showSearch labelInValue options={this.brandList} onChange={value => {}} />,
            },
            {
              label: '盘点时间',
              id: 'inventoryTime',
              rules: [validators.required],
              render: (
                <RangePicker
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              ),
            },
          ]}
        />
        <Row type="flex" justify="start" style={{ marginTop: 20 }}>
          <Col span={3} style={{ textAlign: 'right', fontSize: '12px', color: '#666' }}>
            导入模板：
          </Col>
          <Col span={21}>
            <Button
              type="primary"
              onClick={() => {
                this.downloadTemplate()
              }}
            >
              下载模板
            </Button>
          </Col>
        </Row>
        <Row type="flex" justify="start" style={{ marginTop: 20 }}>
          <Col span={3} style={{ textAlign: 'right', fontSize: '12px', color: '#666' }}>
            导入文件：
          </Col>
          <Col span={21}>
            <Upload
              showUploadList={true}
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
              fileList={this.state.fileList}
              beforeUpload={file => this.beforeUpload(file)}
              onRemove={file => this.onRemove(file)}
            >
              <Button type="primary">上传文件</Button>
            </Upload>
          </Col>
        </Row>
        <Row type="flex" className='row_lable'>
          <Col style={{ textIndent: '0px' }}>上传文件请按照下载模板形式填写，并依照以下规则：</Col>
          <Col>1、表头带红色*项请必填</Col>
          <Col>2、客户类型为分销商时，上级客户编码、上级客户名称必填（上级客户就是所售产品的上级经销商）</Col>
          <Col>3、期间动销数/件不在导入模板中填入，由后台计算得出，公式为：期间动销数=期初库存+期间开单+调入调出-当前实物-当前未到货</Col>
          <Col>{`4、计算出的期间动销数<0时，需填写动销说明`}</Col>
        </Row>
      </Spin>
    )
  }
}
